import os

class PyShell:
    """
    PyShell - a python shell environment
    """
    def __init__(self, path=""):
        if path:
            self._pwd = path
        else:
            self._pwd = os.getcwd()
        self.set_path_shortcut()

    def set_path_shortcut(self):
        self._path_shortcut = os.path.split(self._pwd)[-1]
        if not self._path_shortcut:
            self._path_shortcut = '/'

    def loop(self):
        while True:
            _input = raw_input('[kavinyao@kavinyao-pc %s]$ ' % self._path_shortcut)
            inputs = _input.split(' ')
            if inputs[0] == 'exit':
                return
            elif inputs[0] == 'ls':
                self.list_dir(inputs[1:])
            elif inputs[0] == 'cat':
                self.cat(inputs[1:])

    def list_dir(self, params):
        if len(params) == 0 or params[0] == '.':
            for item in os.listdir(self._pwd):
                print item

    def cat(self, files):
        import mimetypes
        for f in files:
            ftype = mimetypes.guess_type(f)
            if ftype[0] and 'text' in ftype[0]:
                with open(f) as of:
                    for line in of.readlines():
                        print line
            else:
                print '%s not plain text, omitted' % f

if __name__ == '__main__':
    path = os.getcwd()
    pysh = PyShell(path)
    pysh.loop()
